package com.cndym.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


public class ETKUtil {

    //对方

    public static void main(String args[]) {
        Map map = getBillGenResponse("", "88888888");

        System.out.println(aaa("99"));
        ;
        //System.out.println(getBillGenResponse(""));getBillGenResponse("");
        try {
            //System.out.println(getBillGenResponse(""));;
            /*
		
		reqcode
billorgid
billorgcode
putorgid
reqorgid
reqseq
reqpayamount
reqbusicode
reqphone
reqbilldesc
requsetype

		*/
            //getCompMd5(reqcode, billorgid, billorgcode, reqseq, reqpayamount, requsetype)
            String params = "reqcode=5010&billorgid=1000005099&billorgcode=01&reqseq=11&reqpayamount=200&requsetype=91&putorgid=\"\"&reqorgid=\"\"&reqbusicode=\"\"&reqphone=\"\"&reqbilldesc=\"\"";
            //System.out.println(sendUrl("http://113.11.193.237/agent/ebppAction.htm?method=billGen"	, params	, true));
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

    }

    /**
     * 账单申请中得到订单流水号
     *
     * @return
     */
    public static String getReqseq() {
        Calendar c = Calendar.getInstance();
        Date d = c.getTime();
        SimpleDateFormat formatter = new SimpleDateFormat("yyMMdd");
        String dateString = formatter.format(d);
        return dateString + System.currentTimeMillis();
    }

    /**
     * 拆分申请订单得到的数据
     */
    public static Map getBillGenResponse(String returnText, String key) {
        Map<String, String> map = new HashMap<String, String>();
        //	 returnText ="rescode=5011&returncode=0000&returninfo=&reqseq=00181968388058681527&billnum=3061&billstatus=00&sign=8050c430bc532b27e2c67d9e0a9b38a2";
        String[] tmp = returnText.split("&");
        String[] tmp2 = new String[2];
        //tmp2[1]="";
        for (int i = 0; i < tmp.length; i++) {
            //tmp2[0]=tmp[i].split("=")[0];
            if (tmp[i].split("=").length == 1) {
                map.put(tmp[i].split("=")[0], "");
            } else {
                map.put(tmp[i].split("=")[0], tmp[i].split("=")[1]);
            }
            //System.out.println(tmp[i]);
        }
        //判断返回的是否是正确
        if (!map.get("returncode").equals("0000")) {
            map.put("error", "返回码不正确-" + map.get("returncode"));
        } else {
            //验证是否符合签名
            String md5Before = map.get("rescode") + map.get("returncode") + map.get("reqseq") + map.get("billnum") + map.get("billstatus") + "||" + key;
            if (!map.get("sign").equals("") && !Md5.Md5(md5Before).equals(map.get("sign").trim())) {

                map.put("error", "签名遭到篡改");
            } else {
                if (map.get("sign").equals("")) {
                    map.put("error", "没有签名信息");
                }
            }

        }
        return map;
    }

    /**
     * 得到回执并返回
     *
     * @param billid出账机构账单号
     * @param billorgid出账机构编号
     * @param billbusicode业务
     * @param billpaystatus状态
     * @param billpaydesc描述
     * @return map{error,responseText}
     */
    public static Map getReceipt(String billid, String billorgid, String billbusicode, String billpaystatus, String billpaydesc, boolean isUnkown) {
        String billnotifyres = "";
        Map map = new HashMap<String, String>();
		/*
		 *  支付成功(00)
             等待支付(01)
             支付失败(02)
             支付疑问单(03)

		 */
        if (!billpaystatus.equals("00")) {
            map.put("error", "状态为非支付成功状态-" + billpaystatus);
        }
        if (billpaystatus.equals("02")) {
            billnotifyres = "1"; //0:成功1:失败 2:未知
        }

        if (billpaystatus.equals("01") || billpaystatus.equals("03")) {
            billnotifyres = "2"; //0:成功1:失败 2:未知
        }

        if (billpaystatus.equals("00")) {
            billnotifyres = "0";
        }
        if (isUnkown) {
            billnotifyres = "2";
            ;
        }
        map.put("responseText", "billid=" + billid + "&billorgid=" + billorgid + "&billnotifyres=" + billnotifyres);
        return map;
    }

    /**
     * 得到回执后处理逻辑
     */
    public static void doReceipt() {
        String billid = "111"; //在jsp中request.getParameter("billid");
        String billorgid = "222";
        String billpaystatus = "00";
        Map map = getReceipt(billid, billorgid, "", billpaystatus, "", false);
        if (map.get("error") != null) {
            //记录日志 error map.get("error")
            // out.println(map.get("responseText"));//返回给他们所要的格式
        } else {
            //log 成功
            //update table set status=就绪
            // out.println(map.get("responseText"));//返回给他们所要的格式
        }
    }

    /**
     * 在创建订单业务中,组合md5串
     *
     * @param reqcode      请求码
     * @param billorgid    出账机构编号
     * @param billorgcode  出账机构标识
     * @param reqseq       订单流水号
     * @param reqpayamount 订单金额
     * @param requsetype   请求源标识
     * @return
     */
    public static String getCompMd5(String reqcode, String billorgid, String billorgcode, String reqseq, String reqpayamount, String requsetype, String key) {
        return Md5.Md5(reqcode + billorgid + billorgcode + reqseq + reqpayamount + requsetype + "||" + key);
    }

    /**
     * 发送url请求
     *
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String sendUrl(String urlString, String params, boolean isPost) throws Exception {
        // URL url = new URL("http://localhost:8080/webproject/index.jsp?email=1111pk3589@163.com&password=1111123");
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        //

        if (isPost) {
            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

            writer.write(params);
            writer.flush();
            writer.close();
        }
        //System.out.println(conn.getResponseCode());;

        InputStreamReader reder = new InputStreamReader(conn.getInputStream(), "utf-8");

        BufferedReader breader = new BufferedReader(reder);

        // BufferedWriter w = new BufferedWriter(new FileWriter("d:/1.txt"));

        String content = "";
        String result = "";
        while ((content = breader.readLine()) != null) {
            result += content + "\n";
        }
        // w.write(result);
        // w.flush();
        // w.close();
        return result;

    }

    public static String aaa(String begin) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(new Date().getTime());
        StringBuffer orderId = new StringBuffer();
        orderId.append(begin);
        orderId.append(stringBuffer.substring(5));
        // orderId.append(Utils.random(10));
        return orderId.toString();
    }
}
